//
//  HomeCell.swift
//  MyWeiBo
//
//  Created by mac on 15/3/6.
//  Copyright (c) 2015年 gpr. All rights reserved.
//

import UIKit

class HomeCollectionCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!

}

class HomeCell: UITableViewCell {
    // 控件之间的间距
    static let MARGIN : CGFloat = 8
    
    @IBOutlet weak var iconImageView: UIImageView!
    @IBOutlet weak var screen_nameLabel: UILabel!
    @IBOutlet weak var created_atLabel: UILabel!
    @IBOutlet weak var sourcesLabel: UILabel!
    @IBOutlet weak var contentLabel: UILabel!
    @IBOutlet weak var vipImageView: UIImageView!
    @IBOutlet weak var mbIcon: UIImageView!
    
    @IBOutlet weak var photoCollectionView: UICollectionView!
    @IBOutlet weak var photoViewLayout: UICollectionViewFlowLayout!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    
    static let cellSizeWH: CGFloat = 90
    static let cellMargin: CGFloat = 8
    static let photoColumn = 3
    var photos: [UIImage]?
    
    var photoCache = [String: HomeCollectionCell]()
    
    @IBOutlet weak var toolView: UIView!
    // 转发微博
    @IBOutlet weak var retweetStatusContentLabel: UILabel!
    // 选中某张图片的回调
    var imageDidSelected: ((cell: HomeCell, photoIndex:Int ) -> ())?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        retweetStatusContentLabel?.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 2 * HomeCell.MARGIN
        contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 2 * HomeCell.MARGIN
        widthConstraint.constant = HomeCell.cellSizeWH * CGFloat(HomeCell.photoColumn) + ( CGFloat(HomeCell.photoColumn) - 1 ) * HomeCell.cellMargin
        photoViewLayout.minimumInteritemSpacing = HomeCell.cellMargin
        photoViewLayout.minimumLineSpacing = HomeCell.cellMargin
    }
    
    var status: Status? {
        didSet {
            let user = status!.user!
            if let image = ImageTool.getImageFromLocalWithURLString(user.profile_image_url!) {
                self.iconImageView.image = image
            }
            screen_nameLabel.text = user.name
            created_atLabel.text = status!.createTimeStrig!
            if status!.attributString == nil {
                status!.attributString = EmoticonsTool.atrributeTextWithString(status!.text!, lineHeight: contentLabel.font.lineHeight)
            }
            contentLabel.attributedText = status!.attributString
            sourcesLabel.text = status!.source! as? String
            vipImageView.image = status?.user?.verrifyImage
            mbIcon.image = status?.user?.mbImage
            setUpRetweetStatus()
            setUpPhotoView()
        }
    }
    
    func setUpRetweetStatus() {
        if let status = self.status?.retweeted_status {
            if status.user == nil { return }
            retweetStatusContentLabel?.text =  "@" + status.user!.screen_name! + ":" + status.text!
        }
    }
    
    func cellHeightWithStatus(status: Status) -> CGFloat {
        self.status = status
        layoutIfNeeded()
        return CGRectGetMaxY(toolView.frame)
    }
    
    class func cellIDWithStatus(status: Status) -> String {
        if status.retweeted_status == nil {
            return "HomeCell"
        } else {
            return "retweetedHomeCell"
        }
    }

}

extension HomeCell: UICollectionViewDataSource, UICollectionViewDelegate {

    func setUpPhotoView() {
        var imageUrls: [StatusPictureURL]? = status!.statusPictureURL

        heightConstraint.constant = 0
        if imageUrls == nil {
            setUpCollectionheight(0, itemSize: CGSizeZero)
            photos = nil
            return
        }
        let cellmargin = photoViewLayout.minimumInteritemSpacing
        let cellWH = HomeCell.cellSizeWH
        photos = [UIImage]()
        if imageUrls?.count == 1 {
            let urlString = imageUrls![0].thumbnail_pic!
            if let image = ImageTool.getImageFromLocalWithURLString(urlString) {
                photos!.append(image)
                setUpCollectionheight(image.size.height, itemSize: image.size)
            }
            return
        }
        let count = imageUrls!.count
        let row = ( count + HomeCell.photoColumn - 1 )  / HomeCell.photoColumn
        for url in imageUrls! {
            let image = ImageTool.getImageFromLocalWithURLString(url.thumbnail_pic!)
            photos!.append(image!)
        }
        let margin = row > 1 ? Int( HomeCell.cellMargin ) : 0
        let height = row * Int(cellWH) + (row - 1) * margin
        setUpCollectionheight(CGFloat(height), itemSize: CGSizeMake(cellWH , cellWH))
    }
    
    func setUpCollectionheight( height: CGFloat, itemSize: CGSize ){
        heightConstraint.constant = height
        if height != 0 {
            photoViewLayout.itemSize = itemSize
        }
        photoCollectionView.reloadData()
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photos?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("HomeCollectionCell", forIndexPath: indexPath) as? HomeCollectionCell
        let image = photos![indexPath.item]
        cell!.imageView.image = image
    
        return cell!
    }
    
    // MARK: UICollectionViewDelegate
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if imageDidSelected != nil {
            imageDidSelected!(cell: self, photoIndex: indexPath.item)
        }
    }
}


